package com.car.loan.project.system.controller;

import com.car.loan.common.constant.UserConstants;
import com.car.loan.common.utils.SecurityUtils;
import com.car.loan.framework.web.domain.BaseEntity;
import com.car.loan.project.system.domain.SysRole;
import com.car.loan.project.system.domain.vo.SysDeptByUserVo;
import com.car.loan.project.system.domain.vo.SysDeptByUserVo.DeptUser;
import com.car.loan.project.system.service.ISysDeptService;
import com.car.loan.project.system.service.ISysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.car.loan.framework.aspectj.lang.annotation.Log;
import com.car.loan.framework.aspectj.lang.enums.BusinessType;
import com.car.loan.framework.web.controller.BaseController;
import com.car.loan.framework.web.domain.AjaxResult;
import com.car.loan.framework.web.page.TableDataInfo;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
@Api(value = "系统角色信息接口", tags = "系统角色信息接口")
public class SysRoleController extends BaseController {

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;


    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    @ApiOperation("角色信息列表")
    public TableDataInfo list(SysRole role) {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    @ApiOperation("根据角色编号获取详细信息")
    public AjaxResult getInfo(@PathVariable Long roleId) {
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增角色")
    public AjaxResult add(@RequestBody SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改保存角色")
    public AjaxResult edit(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRole(role));
    }


    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @ApiOperation("角色状态修改")
    public AjaxResult changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 用户角色分配
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeUsers")
    @ApiOperation("用户角色分配")
    public AjaxResult changeUsers(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.updateRoleUsers(role));
    }


    /**
     * 获取用户选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionUserSelect")
    @ApiOperation("获取用户选择框列表")
    public AjaxResult optionUserSelect(Long roleId) {
        SysRole sysRole = new SysRole();
        sysRole.setRoleId(roleId);
        //获取当前角色用户
        List<Long> userListByRoleId = roleService.findUserListByRoleId(sysRole);
        //获取用户树
        List<SysDeptByUserVo> sysDeptByUserVos = deptService.buildDeptUserTree(sysRole);
        sysDeptByUserVos.forEach(sysDeptByUserVo -> {
            roleSysDeptByUserVoTree(sysDeptByUserVo, userListByRoleId);
        });
        return AjaxResult.success(sysDeptByUserVos);
    }


    private void roleSysDeptByUserVoTree(SysDeptByUserVo sysDeptByUserVo, List<Long> userIds) {
        List<DeptUser> deptUsers = sysDeptByUserVo.getDeptUsers();
        if (null != deptUsers && deptUsers.size() > 0) {
            deptUsers.forEach(deptUser -> {
                if (userIds.contains(deptUser.getId())) {
                    deptUser.setSelect(true);
                }
            });
            sysDeptByUserVo.setDeptUsers(deptUsers);
        }
        List<SysDeptByUserVo> children = sysDeptByUserVo.getChildren();
        if (null != children && children.size() > 0) {
            children.forEach(sysDeptByUserVo1 -> {
                roleSysDeptByUserVoTree(sysDeptByUserVo1, userIds);
            });
            sysDeptByUserVo.setChildren(children);
        }
    }



    /**
     * 删除岗位
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleId}")
    @ApiOperation("删除角色")
    public AjaxResult remove(@PathVariable Long roleId) {
        roleService.checkRoleAllowed(new SysRole(roleId));
        return toAjax(roleService.deleteRoleById(roleId));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    @ApiOperation("获取角色选择框列表")
    public AjaxResult optionselect() {
        return AjaxResult.success(roleService.selectRoleAll());
    }




}